package service

import (
	"GoKill/help"
	"GoKill/models"
	"github.com/gin-gonic/gin"
	"golang.org/x/net/context"
	"gorm.io/gorm"
)

var ctx = context.Background()

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  "用户名和密码不能为空",
		})
		return
	}
	//MD5加密，由于为了方便就不加了
	data := new(models.User)
	err := models.DB.Where("name=? AND password=?", username, password).First(&data).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(200, gin.H{
				"code": -1,
				"msg":  "用户名密码错误",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  "内部错误" + err.Error(),
		})
	}

	//构建token，在help包下
	token, err1 := help.GenerateToken(data.ID, data.Username)
	if err1 != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  "token error" + err.Error(),
		})
	}
	models.RDB.Set(ctx, "usergo", token, 0).Err()
	if err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  "token error" + err.Error(),
		})
	}

	c.JSON(200, gin.H{
		"code":  200,
		"data":  data,
		"token": token,
	})
}
